from rest_framework import serializers
from user.models import User
from django_redis import get_redis_connection
import re,jwt
from user.utils import Authenticate
from django.conf import settings
class UsermodelSerializers(serializers.ModelSerializer):
    # 验证码只参与反序列化
    sms_code = serializers.CharField(write_only=True)
    username = serializers.CharField(max_length=15,min_length=1)
    password = serializers.CharField(max_length=20,min_length=5,write_only=True)
    token = serializers.CharField(read_only=True)
    class Meta:
        model = User

        fields = [
            'id',
            'username',
            'password',
            'mobile',
            'token',
            'avatar',
            'sms_code'
        ]


    # 验证手机号格式
    def validated_mobile(self, value):

        if not re.match('^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

    def validate(self, attrs):
        # 连接redis数据库
        sms_code_redis = get_redis_connection('sms_code')
        # 获取用户输入的手机号和验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        username = attrs.get('username')
        password = attrs.get('password')

        # 获取redis中用户手机号的验证码
        mobile_redis = sms_code_redis.get('sms_%s' % mobile)

        if not mobile_redis:
            raise serializers.ValidationError('验证码过期')

        if sms_code != mobile_redis.decode():
            raise serializers.ValidationError('验证码错误')

        print(mobile_redis)
        from django.contrib.auth import authenticate
        return attrs

    def create(self, validated_data):


        validated_data.pop('sms_code')
        user = super().create(validated_data)


        user.set_password(validated_data['password'])

        user.save()


        payload = {"user_id": user.id, "username": user.username}

        token = jwt.encode(payload,settings.SECRET_KEY,algorithm='HS256')
        user.token = token
        return user



